package com.xinxin.o2o.controller.shopcontroller;

import com.google.code.kaptcha.Producer;
import com.xinxin.o2o.dto.ShopExecution;
import com.xinxin.o2o.enums.GlobalCode;
import com.xinxin.o2o.model.Area;
import com.xinxin.o2o.model.PersonInfo;
import com.xinxin.o2o.model.Shop;
import com.xinxin.o2o.model.ShopCategory;
import com.xinxin.o2o.response.Response;
import com.xinxin.o2o.service.AreaService;
import com.xinxin.o2o.service.ShopCategoryService;
import com.xinxin.o2o.service.ShopService;
import com.xinxin.o2o.util.PathUtil;
import com.xinxin.o2o.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import static com.xinxin.o2o.enums.ShopStateEnum.CHECK;
import static com.xinxin.o2o.enums.ShopStateEnum.SUCCESS;

/**
 * @author 史鑫鑫
 * @date 2019-08-13 23:53
 */
@Api(tags = {"店铺管理模块"}, produces = "application/json")
@RestController
@RequestMapping("/api/shop/")
public class ShopManagementController {
    private Logger logger = LoggerFactory.getLogger(ShopManagementController.class);

    @Autowired
    private ShopService shopService;

    @Autowired
    AreaService areaService;

    @Autowired
    ShopCategoryService shopCategoryService;

    @Autowired
    private Producer captchaProducer;

    @ApiOperation(value = "注册店铺")
    @PostMapping("/registerShop")
    public Response registerShop(@RequestParam MultipartFile shopImg,
                                 @RequestParam String shopName,
                                 @RequestParam String shopDesc,
                                 @RequestParam String shopAddr,
                                 @RequestParam String phone,
                                 @RequestParam Long areaId,
                                 @RequestParam Long shopCategoryId,
                                 HttpSession httpSession) {
        logger.info("====开始 registerShop===");
        logger.info("===registerShop:" + httpSession.getId() + "===");
        Shop shop = new Shop();
        shop.setShopName(shopName);
        shop.setShopDesc(shopDesc);
        shop.setShopAddr(shopAddr);
        shop.setPhone(phone);

        PersonInfo personInfo = new PersonInfo();
        personInfo.setUserId(1L);
//        PersonInfo owner = (PersonInfo) session.getAttribute("user");
        shop.setOwner(personInfo);

        Area area = new Area();
        area.setAreaId(areaId);
        shop.setArea(area);

        ShopCategory shopCategory = new ShopCategory();
        shopCategory.setShopCategoryId(shopCategoryId);
        shop.setShopCategory(shopCategory);

        ShopExecution shopExecution = null;
        try {
            shopExecution = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
        } catch (IOException e) {
            return ResponseUtil.error(-2, e.getMessage());
        }
        if (CHECK.getState().equals(shopExecution.getState())) {
            logger.info("====完成 registerShop===");
            return ResponseUtil.success();
        } else {
            return ResponseUtil.error(shopExecution.getState(), shopExecution.getStateInfo());
        }
    }

    @ApiOperation(value = "获取区域信息")
    @GetMapping("/areas")
    public Response getAreas() {
        try {
            return ResponseUtil.success(areaService.getAreaList());
        } catch (Exception e) {
            return ResponseUtil.error(3001, e.getMessage());
        }
    }

    @ApiOperation(value = "获取店铺类别信息")
    @GetMapping("/shopCategories")
    public Response getShopCategories() {
        try {
            return ResponseUtil.success(shopCategoryService.getShopCategoryList(new ShopCategory()));
        } catch (Exception e) {
            return ResponseUtil.error(3001, e.getMessage());
        }
    }

    /**
     * 根据shopId返回店铺信息
     *
     * @param shopId shopId
     * @return 店铺信息
     */
    @ApiOperation(value = "通过id获取店铺信息")
    @GetMapping("/getShopById")
    public Response getShopById(@RequestParam("shopId") Long shopId) {
        Shop shop = shopService.getByShopId(shopId);
        if (shop == null) {
            return ResponseUtil.error(3001, "空的店铺");
        }
        return ResponseUtil.success(shop);
    }

    @GetMapping("/getShopImgById")
    public void getShopImgById(@RequestParam("shopId") Long shopId, HttpServletResponse httpServletResponse, HttpSession httpSession) throws Exception {
        logger.info("===getShopImgById:" + httpSession.getId() + "===");
        byte[] shopImgByte;
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        try {
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            Shop shop = shopService.getByShopId(shopId);
            BufferedImage image = ImageIO.read(new FileInputStream(PathUtil.getImgBasePath() + shop.getShopImg()));
            ImageIO.write(image, "png", pngOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/png类型，使用response输出流输出图片的byte数组
        shopImgByte = pngOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/png");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(shopImgByte);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 修改店铺信心
     *
     * @param shopImg  图片
     * @param shopDesc 店铺描述
     * @param shopAddr 店铺地址
     * @param phone    电话
     * @param areaId   地区id
     * @return 修改结果
     */
    @ApiOperation(value = "更新店铺信息")
    @PutMapping("/modifyShop")
    public Response modifyShop(@RequestParam(required = false, value = "shopImg") MultipartFile shopImg,
                               @RequestParam Long shopId,
                               @RequestParam String shopName,
                               @RequestParam String shopDesc,
                               @RequestParam String shopAddr,
                               @RequestParam String phone,
                               @RequestParam Long areaId,
                               HttpSession httpSession) {
        logger.info("====开始 modifyShop===");
        logger.info("===modifyShop:" + httpSession.getId() + "===");
        Shop shop = new Shop();
        shop.setShopId(shopId);
        shop.setShopName(shopName);
        shop.setShopDesc(shopDesc);
        shop.setShopAddr(shopAddr);
        shop.setPhone(phone);

        Area area = new Area();
        area.setAreaId(areaId);
        shop.setArea(area);

        ShopExecution shopExecution;
        try {
            if (shopImg == null) {
                shopExecution = shopService.modifyShop(shop, null, null);
            } else {
                shopExecution = shopService.modifyShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
            }
        } catch (IOException e) {
            return ResponseUtil.error(-2, e.getMessage());
        }
        if (SUCCESS.getState().equals(shopExecution.getState())) {
            logger.info("====完成 modifyShop===");
            return ResponseUtil.success();
        } else {
            return ResponseUtil.error(shopExecution.getState(), shopExecution.getStateInfo());
        }
    }

    @ApiOperation(value = "获取店铺列表")
    @GetMapping("/getShopList")
    public Response getShopList(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "size", defaultValue = "10") int size) {
        PersonInfo personInfo = new PersonInfo();
        personInfo.setUserId(1L);
        try {
            Shop shopCondition = new Shop();
            shopCondition.setOwner(personInfo);
            ShopExecution shopExecution = shopService.getShopList(shopCondition, page, size);
            if (SUCCESS.getState().equals(shopExecution.getState())) {
                return ResponseUtil.success(shopExecution.getShopList());
            } else {
                return ResponseUtil.error(GlobalCode.INNER_ERROR);
            }
        } catch (Exception e) {
            return ResponseUtil.error(-2, e.getMessage());
        }
    }
}

